<template>
  <!-- 增加酒店窗口 -->
  <div class="collection">
    <el-dialog
      title="添加酒店"
      :visible.sync="addDialogVisible"
      width="60%"
      center
      @close="addDialogClosed"
    >
      <el-form :model="addForm" ref="addFormRef" label-width="100px">
        <el-form-item label="酒店名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="酒店等级" prop="rank">
          <el-select
            v-model="addForm.rank"
            placeholder="酒店等级"
            clearable
            style="width: 100%"
            class="filter-item"
          >
            <el-option
              v-for="item in rank"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="酒店价格" prop="price">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>
        <el-form-item label="酒店地址" prop="position">
          <el-input v-model="addForm.position"></el-input>
        </el-form-item>
        <el-form-item label="交通路线" prop="traffic">
          <el-input v-model="addForm.traffic"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="traffic">
          <el-input v-model="addForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addHotelInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改酒店的对话框 -->
    <el-dialog
      title="修改酒店"
      :visible.sync="editDialogVisible"
      width="60%"
      center
      @close="editDialogClosed"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item label="酒店名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="酒店等级" prop="rank">
          <el-select
            v-model="editForm.rank"
            placeholder="酒店等级"
            clearable
            style="width: 100%"
            class="filter-item"
          >
            <el-option
              v-for="item in rank"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="酒店价格" prop="price">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="酒店地址" prop="position">
          <el-input v-model="editForm.position"></el-input>
        </el-form-item>
        <el-form-item label="交通路线" prop="traffic">
          <el-input v-model="editForm.traffic"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="traffic">
          <el-input v-model="editForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editHotelInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <div class="filter-container">
        <el-input
          v-model="queryInfo.name"
          placeholder="酒店名"
          style="width: 100px;"
          class="filter-item"
          @keyup.enter.native="getHotelList"
        />

        <el-input
          v-model="queryInfo.position"
          placeholder="酒店地址"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="getHotelList"
        />
        <el-select
          v-model="queryInfo.rank"
          placeholder="酒店等级"
          clearable
          style="width: 120px"
          class="filter-item"
        >
          <el-option
            v-for="item in rank"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>

        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="getHotelList"
          >Search</el-button
        >

        <el-button type="primary" @click="addDialogVisible = true"
          >添加酒店</el-button
        >
        <el-button
          :loading="downloadLoading"
          type="primary"
          icon="el-icon-document"
          @click="handleDownload"
          >导出excel</el-button
        >
      </div>

      <div class="table-box">
        <el-table
          border
          stripe
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <pre>{{ scope.row }}</pre>
            </template>
          </el-table-column>
          <!-- <el-table-column type="index"></el-table-column> -->

          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="id"
            label="ID"
            width
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="酒店名"
            width
            align="center"
          ></el-table-column>
          <el-table-column
            prop="position"
            label="酒店地址"
            width
            align="center"
          ></el-table-column>
          <el-table-column prop="price" label="酒店价格" width align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.price === 0">免费</el-tag>
              <el-tag type="info" v-else>{{ scope.row.price }}/人</el-tag>
            </template></el-table-column
          >
          <el-table-column prop="rank" label="酒店等级" width align="center">
            <template slot-scope="scope">
              <el-rate disabled v-model="scope.row.rank"></el-rate>
            </template>
          </el-table-column>
          <el-table-column
            prop="tel"
            label="联系电话"
            width
            align="center"
          ></el-table-column>

          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-tooltip
                effect="dark"
                content="删除"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeHotelById(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="编辑"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDialog(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="查看"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="success"
                  icon="el-icon-search"
                  size="small"
                  @click="handleOperate(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Collection',
  data() {
    return {
      tableData: [],
      rank: [0, 1, 2, 3, 4, 5],
      // 获取酒店列表的参数对象
      queryInfo: {
        name: '',
        rank: '',
        position: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      total: 0,
      // 控制添加酒店对话框的显示与隐藏
      addDialogVisible: false,
      list: null,
      multipleSelection: [],
      filename: '',
      downloadLoading: false,

      // 控制修改酒店对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的酒店信息对象
      editForm: {},
      addForm: {}
    }
  },
  created() {
    this.getHotelList()
  },
  methods: {
    // 导出
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 下载
    handleDownload() {
      if (this.multipleSelection.length) {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            'ID',
            '酒店名',
            '酒店地址',
            '酒店价格',
            '酒店等级',
            '交通路线',
            '联系电话'
          ]
          const filterVal = [
            'id',
            'name',
            'position',
            'price',
            'rank',
            'traffic',
            'tel'
          ]
          const list = this.multipleSelection
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename
          })
          this.$refs.multipleTable.clearSelection()
          this.downloadLoading = false
        })
      } else {
        this.$message({
          message: 'Please select at least one item',
          type: 'warning'
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleOperate(ele) {
      // console.log(ele)
      this.$router.push({
        path: '/tables/details'
      })
    },
    async getHotelList() {
      // this.$http.defaults.headers['IP'] = location.href.toString()
      // this.$http.defaults.headers['token'] = window.sessionStorage.getItem(
      //   'token'
      // )
      const { data: res } = await this.$http.get('/hotels', {
        params: this.queryInfo
      })
      if (res.status !== 201) {
        return this.$message.error('获取酒店列表失败！')
      }
      // console.log(res.hotel)
      this.tableData = res.hotel
      this.total = res.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getHotelList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getHotelList()
    },
    // 监听 switch 开关状态的改变
    // async userStateChanged(userinfo) {
    //   console.log(userinfo)
    //   const { data: res } = await this.$http.put(
    //     `users/${userinfo.id}/state/${userinfo.mg_state}`
    //   )
    //   if (res.meta.status !== 200) {
    //     userinfo.mg_state = !userinfo.mg_state
    //     return this.$message.error('更新酒店状态失败！')
    //   }
    //   this.$message.success('更新酒店状态成功！')
    // },

    // 展示编辑酒店的对话框
    async showEditDialog(form) {
      this.editForm = form
      this.editDialogVisible = true
    },
    // 展示添加酒店的对话框
    async showAddDialog(form) {
      this.addForm = form
      this.addDialogVisible = true
    },
    // 监听修改酒店对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 监听添加酒店对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 修改酒店信息并提交
    editHotelInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改酒店信息的数据请求
        const { data: res } = await this.$http.put('/hotel', {
          id: this.editForm.id,
          position: this.editForm.position,
          traffic: this.editForm.traffic,
          tel: this.editForm.tel,
          name: this.editForm.name,
          price: this.editForm.price,
          rank: this.editForm.rank
        })

        if (res.status !== 201) {
          return this.$message.error('更新酒店信息失败！')
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getHotelList()
        // 提示修改成功
        this.$message.success('更新酒店信息成功！')
      })
    },
    addHotelInfo() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }

        // 发起请求添加酒店
        // 酒店的名称，必须是唯一的
        const { data: res } = await this.$http.post('/hotel', this.addForm)

        if (res.status !== 201) {
          return this.$message.error('添加酒店失败！')
        }

        this.$message.success('添加酒店成功！')
        this.$router.push('/note/list')
      })
    },
    // 根据Id删除对应的酒店信息
    async removeHotelById(id) {
      // 弹框询问酒店是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该酒店, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果酒店确认删除，则返回值为字符串 confirm
      // 如果酒店取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('/hotel', {
        data: { id: id }
      })

      if (res.status !== 201) {
        return this.$message.error('删除酒店失败！')
      }
      this.$message.success('删除酒店成功！')
      this.getHotelList()
    }
  }
}
</script>

<style lang="stylus"></style>
